<template>
	<v-stage :config="{ width: props.width, height: props.height }">
		<v-layer>
			<template v-for="(value, key) in inferenceResult" :key="key">
				<template v-if="value?.length">
					<v-group
						v-for="graph in value"
						:key="graph.konvaGraphConfig.id"
						:config="graph.konvaGraphConfig"
					>
						<template v-if="graph.graphsConfigItems?.length">
							<KonvaGraphNode
								v-for="(child, k) in graph.graphsConfigItems"
								:key="k"
								:node="child"
							/>
						</template>
					</v-group>
				</template>
			</template>
		</v-layer>
	</v-stage>
</template>

<script setup lang="ts">
defineOptions({
	name: "OSDInferenceOverlay",
	inheritAttrs: false,
});

import { reactive, computed, watch, type PropType } from "vue";
import { isNumber } from "lodash-es";
import { useInferenceResultStoreHook } from "@/vue-stores-pinia/modules/inference-result";
import { updateKonvaConfigBasedOnLatestSize, getRoiLineConfig } from "@/utils/data-transformers";
import type { T_RoiSingleOfApi } from "@/types/raw-data";
import type { KonvaGroupConfig } from "@/types/konva";

const props = defineProps({
	width: {
		type: Number,
		default: 0,
	},
	height: {
		type: Number,
		default: 0,
	},
	cameraId: {
		type: String,
		default: "",
	},
	currentTopics: {
		type: Array as PropType<string[]>,
		default: () => [],
	},
	currentRois: {
		type: Array as PropType<T_RoiSingleOfApi[]>,
		default: () => [],
	},
});

const inferenceResultStore = useInferenceResultStoreHook();
const inferenceResult = computed<Record<string, any>>(() => {
	const result = inferenceResultStore.getResultsByCondition({
		cameraId: props.cameraId,
		topics: props.currentTopics,
	});
	
	if (currentRoi.roiKey) {
		result["roi-" + currentRoi.roiKey] = currentRoi.roiConfig; // 合并 ROI 配置
	}
	return result;
});

const currentRoi = reactive<{ roiKey: number | null; roiConfig: KonvaGroupConfig[] }>({
	roiKey: null,
	roiConfig: [],
});

watch(
	() => props.currentRois,
	(value) => {
		if (value) {
			const roiConfig = getRoiLineConfig(value);
			currentRoi.roiConfig = updateKonvaConfigBasedOnLatestSize(
				[roiConfig],
				props.width,
				props.height
			);
			currentRoi.roiKey = performance.now();
		}
	}
);

watch(
	[() => props.width, () => props.height],
	([width, height]: [number, number]) => {
		if (isNumber(width) && isNumber(height)) {
			// 更新每个 camera 的最新矩形大小
			currentRoi.roiConfig = updateKonvaConfigBasedOnLatestSize(
				currentRoi.roiConfig,
				width,
				height
			);
			currentRoi.roiKey = performance.now();
		}
	},
	{ immediate: true }
);
</script>

